﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using eTMS.Controllers.BoMonService;
using eTMS.Controllers;
using eTMS.Commons;
using eTMS.Controllers.KhoaService;
namespace eTMS.Forms.ManageList{
    public partial class FrmBoMon : eTMS.Controls.BaseForm
    {
        public FrmBoMon()
        {
            InitializeComponent();
        }
        #region Variables
        private BoMonController controller = new BoMonController();
        #endregion
        #region Screen Functions
        //Load All lable text
        private void LoadLanguage(){
			this.Text=BoMonStringMapping.BoMon;
			this.labelFormTitle.Text=Constants.APP_ADMINISTRATION+" "+BoMonStringMapping.BoMon;
			this.groupBoxDetail.Text=Constants.APP_DETAIL;
			this.groupBoxList.Text=Constants.APP_LIST;
			this.ColumnSTT.HeaderText=Constants.APP_INDEX;
			labelMaBoMon.Text=BoMonStringMapping.MaBoMon;
			ColumnMaBoMon.HeaderText=BoMonStringMapping.MaBoMon;
			labelTenBoMon.Text=BoMonStringMapping.TenBoMon;
			ColumnTenBoMon.HeaderText=BoMonStringMapping.TenBoMon;
			labelMoTaBoMon.Text=BoMonStringMapping.MoTaBoMon;
			ColumnMoTaBoMon.HeaderText=BoMonStringMapping.MoTaBoMon;
			labelKhoa_ID.Text=BoMonStringMapping.Khoa_ID;
		    //Search
		    this.groupBoxFilter.Text=Constants.APP_SEARCH;
			cbkMaBoMonFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelMaBoMonFilter.Text=BoMonStringMapping.MaBoMon;
			cbkTenBoMonFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelTenBoMonFilter.Text=BoMonStringMapping.TenBoMon;
			cbkMoTaBoMonFilterExact.Text=Constants.APP_SEARCH_EXACT;
			labelMoTaBoMonFilter.Text=BoMonStringMapping.MoTaBoMon;
		    //end
        }
        //Get entity selected from datagrid
        private BoMonEntity GetObject(){
		    BoMonEntity o=controller.MapDataRowToObject(((DataRowView)gridData.SelectedRows[0].DataBoundItem).Row);
		    return o;
        }        
        //Get entites selected from datagrid
        private List<DataRow> GetSelectedDataRows(){
		    List<DataRow> ls=new List<DataRow>();
            for(int i=0;i<gridData.SelectedRows.Count;i++){
                ls.Add(GetDataRow(gridData.SelectedRows[i].Index));
            }
		    return ls;
        }
        //Get the selected data row in datagrid
        private DataRow GetSelectedDataRow(){
			DataRow row=GetDataRow(gridData.SelectedRows[0].Index);
		    return row;
        }
         //Get the selected data row in datagrid
        private DataRow GetDataRow(int index){
			DataRow row=((DataRowView)gridData.Rows[index].DataBoundItem).Row;
		    return row;
        }
        //Reset all textbox
        private void ClearScreen(){
			txtMaBoMon.Text="";
			txtTenBoMon.Text="";
			txtMoTaBoMon.Text="";
			errorProviderData.Clear();
        }
        //Lock-Unlock control in screen
        private void LockScreen(bool IsLocked){            
            ucCommand.LockControl(IsLocked);
			txtMaBoMon.ReadOnly = IsLocked;
			txtTenBoMon.ReadOnly = IsLocked;
			txtMoTaBoMon.ReadOnly = IsLocked;
			txtKhoa_ID.ReadOnly = IsLocked;
        }
        //Copy data from control in screen to object
        private void CopyFromSreen(BoMonEntity o){
			 o.MaBoMon=Convert.ToString(txtMaBoMon.Text);
			 o.TenBoMon=Convert.ToString(txtTenBoMon.Text);
			 o.MoTaBoMon=Convert.ToString(txtMoTaBoMon.Text);
			 o.Khoa_ID=Convert.ToInt32(txtKhoa_ID.SelectedValue);
        }
        //Bind data from object to control in screen
        private void CopyToSreen(BoMonEntity o){
		    if(!o.IsNullMaBoMon){
			txtMaBoMon.Text=Convert.ToString(o.MaBoMon);
		    }
		    if(!o.IsNullTenBoMon){
			txtTenBoMon.Text=Convert.ToString(o.TenBoMon);
		    }
		    if(!o.IsNullMoTaBoMon){
			txtMoTaBoMon.Text=Convert.ToString(o.MoTaBoMon);
		    }
            if(!o.IsNullKhoa_ID){
				txtKhoa_ID.SelectedValue=o.Khoa_ID;
			}
			else{
				txtKhoa_ID.SelectedValue=null;
			}
        }
        //Validate all data from control in screen before Save data
        protected bool ValidateScreen(){
		    bool result=true;
			if((txtKhoa_ID.SelectedIndex<0)){
				txtKhoa_ID.Focus();
				errorProviderData.SetError(txtKhoa_ID, Constants.MSS_ERROR_DROPDOWN);
				result=false;
			}
			else{
				errorProviderData.SetError (txtKhoa_ID, "");
			}
		    if(!result){
				ShowInfo(Constants.MSS_REQUIRE_FIELD);
		    }
		    if(result){
				//Check if exists MaBoMon				
				bool existsMaBoMon=controller.CheckExistsMaBoMon(txtMaBoMon.Text);
				bool editexists=false;
				if(Flag==ACTIONENUM.Edit){
					DataRow row = GetSelectedDataRow();
					string newVal=txtMaBoMon.Text;
					editexists=Convert.ToString(row["MaBoMon"])!=Convert.ToString(newVal);
				}
				if(existsMaBoMon&&((Flag==ACTIONENUM.AddNew)||editexists)){
					result = false; 					
					errorProviderData.SetError(txtMaBoMon,Constants.MSS_ERROR_DATA_UNIQUE);
					txtMaBoMon.Focus();
					ShowInfo(Constants.MSS_ERROR_EXISTS_DATA);
				}
				else
				{
					errorProviderData.SetError (txtMaBoMon, "");
				}
			}
		    return result;
        }
        //Copy data from selected object to control in screen
        private void BindInfo(){
			if (gridData.SelectedRows.Count == 0) return;
			if(gridData.SelectedRows[0].Index<gridData.Rows.Count){
				BoMonEntity o=GetObject();	
				CopyToSreen(o);
		    }
        }    
        #endregion
        #region Business
        //AddNew data to database
        private bool AddNewData()
        {
			bool rval=false;
            controller.ResetObject();		
		    CopyFromSreen(controller.BoMonObject);		    
            rval=controller.AddNew();
            if(rval){
				DataRow row=controller.Table.NewRow();
				row["STT"]=controller.Table.Rows.Count+1;
				controller.MapObjectToDataRow(row);
				controller.Table.Rows.Add(row);
				gridData.DataSource=null;
				gridData.DataSource=controller.Table;
            }
            return rval;
        }
        //Update data to database
        private bool UpdateData()
        {      
			DataRow row=GetSelectedDataRow();
            controller.LoadObject((Int32)row["BoMon_ID"]);		
		    CopyFromSreen(controller.BoMonObject);
		    bool rval=controller.Update();
            if(rval){
				controller.MapObjectToDataRow(row);
				gridData.InvalidateRow(gridData.SelectedRows[0].Index);
            }
            return rval;
        }
        //Delete data from database
        private bool DeleteData()
        {
            List<DataRow> ls=GetSelectedDataRows();
            if(ls.Count==0)return false;  
            bool rval=true; 
            try{
                gridData.DataSource = null;
				foreach(DataRow row in ls){
					if(controller.DeleteByID((Int32)row["BoMon_ID"])){
						 this.controller.Table.Rows.Remove(row);
					}	
					else
					{
						rval=false;
					}				
				}
				this.controller.ResetTableIndex();
                gridData.DataSource = this.controller.Table;
            }
            catch{
				return false;
            }
            return true;
        }        
        #endregion
        #region DataBinding 
        //Bind data to datagrid
        private void LoadData(){
            gridData.AutoGenerateColumns = false;
            gridData.DataSource=controller.Table;     
            gridData.AutoResizeColumns();       
        }
        #endregion
        private void DisplayKhoa()
        {
            KhoaController.LoadAllKhoa(false);
            treeView1.Nodes.Clear();
            TreeNode root = new TreeNode(Constants.APP_ALL);
            treeView1.Nodes.Add(root);
            root.ImageIndex = 0;
            root.SelectedImageIndex = 0;
            foreach (KhoaEntity oKhoa in KhoaController.ListKhoaStatic)
            {
                TreeNode node = new TreeNode();
                node.Text = oKhoa.TenKhoa;
                node.Tag = oKhoa;
                node.ImageIndex = 1;
                node.SelectedImageIndex = 1;
                root.Nodes.Add(node);
            }
            root.Expand();
        }
        #region Windows Control EventHandlers
        private void FrmBoMon_Load(object sender, EventArgs e)
        {
            DisplayKhoa();
            LoadLanguage();
            LoadData();
            LockScreen(true);
            this.groupBoxFilter.ToggleCollapsed();
        }       
		private void gridData_RowEnter(object sender, DataGridViewCellEventArgs e)
        {
			BindInfo();
        }   
        private void ucCommand_OnAddNew(object sender, EventArgs e)
        {
			ClearScreen();
            LockScreen(false);
            Flag=ACTIONENUM.AddNew;
			txtMaBoMon.Focus();
        }
        private void ucCommand_OnDelete(object sender, EventArgs e)
        {
			if(gridData.SelectedRows.Count==0){
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            if(!Confirm(Constants.MSS_CONFIRM_DELETE))return;
            DeleteData();
			this.gridData.Focus();
        }
        private void ucCommand_OnEdit(object sender, EventArgs e)
        {
			if(gridData.SelectedRows.Count==0){
                ShowInfo(Constants.MSS_CHOOSERECORD_REQUIRE);
                return;
            }
            LockScreen(false);
            Flag=ACTIONENUM.Edit;
			txtMaBoMon.Focus();
        }
        private void ucCommand_OnSave(object sender, EventArgs e)
        {
			if(!ValidateScreen())
				return;
            if(Flag==ACTIONENUM.Edit){
                if(UpdateData()){
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else{
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
                gridData.Focus();
            }
            else{
                if(AddNewData()){
                    ShowInfo(Constants.MSS_SAVE_SUCCESS);
                }
                else{
                    ShowWarning(Constants.MSS_SAVE_FAILE);
                }
            }
            LockScreen(true);
            Flag=ACTIONENUM.None;
        }
        private void ucCommand_OnSkip(object sender, EventArgs e)
        {
			LockScreen(true);  
			if(Flag==ACTIONENUM.AddNew){			
				ClearScreen();    
				ucCommand.SetFocusAddNew();
			}
			else if(Flag==ACTIONENUM.Edit){				
				BindInfo();
				this.gridData.Focus();
			}      
            Flag=ACTIONENUM.None;
        }
        #endregion   
        #region Filters
        private string GetFilter(){
			string strFilter="";
			if(txtMaBoMonFilter.Text.Trim()!=""){
				if(cbkMaBoMonFilterExact.Checked){
					strFilter+=" AND MaBoMon='"+txtMaBoMonFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND MaBoMon LIKE '%"+txtMaBoMonFilter.Text.Trim()+"%'";
				}
			}	
			if(txtTenBoMonFilter.Text.Trim()!=""){
				if(cbkTenBoMonFilterExact.Checked){
					strFilter+=" AND TenBoMon='"+txtTenBoMonFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND TenBoMon LIKE '%"+txtTenBoMonFilter.Text.Trim()+"%'";
				}
			}	
			if(txtMoTaBoMonFilter.Text.Trim()!=""){
				if(cbkMoTaBoMonFilterExact.Checked){
					strFilter+=" AND MoTaBoMon='"+txtMoTaBoMonFilter.Text.Trim()+"'";
				}
				else{
					strFilter+=" AND MoTaBoMon LIKE '%"+txtMoTaBoMonFilter.Text.Trim()+"%'";
				}
			}	
			if(treeView1.SelectedNode!=null && treeView1.SelectedNode.Tag is KhoaEntity){
                strFilter += " AND Khoa_ID='" + ((KhoaEntity)treeView1.SelectedNode.Tag).Khoa_ID.ToString() + "'";	
			}
			if(strFilter.Length>0)
				strFilter=strFilter.Substring(4);
			return strFilter;
		}
		private void FilterData(){		
            gridData.ClearSelection();
			controller.Table.DefaultView.RowFilter=GetFilter();
		}
        private void btnSearch_Click(object sender, EventArgs e)
        {
			FilterData();
        }
        #endregion   

        private void treeView1_AfterSelect(object sender, TreeViewEventArgs e)
        {
            FilterData();
        }

        private void treeKhoaBoMonMonHocLopTinChi1_DragDrop(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(typeof(List<DataRow>)) != null)
            {
                TreeNode targetNode = treeView1.GetNodeAt(treeView1.PointToClient(new Point(e.X, e.Y)));
                if ((targetNode != null) || (!(targetNode.Tag is KhoaEntity)))
                {
                    if (Confirm("Bạn thực sự muốn chuyển các bộ môn đã chọn vào khoa " + targetNode.Text + " không?"))
                    {
                        List<DataRow> ls = (List<DataRow>)e.Data.GetData(typeof(List<DataRow>));
                        foreach (DataRow row in ls)
                        {
                            controller.LoadObject((Int32)row["BoMon_ID"]);
                            controller.BoMonObject.Khoa_ID = ((KhoaEntity)targetNode.Tag).Khoa_ID;
                            controller.Update();
                            row["Khoa_ID"] = controller.BoMonObject.Khoa_ID;
                        }
                    }
                }
            }
        }

        private void treeKhoaBoMonMonHocLopTinChi1_DragEnter(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(typeof(List<DataRow>)) != null)
            {
                e.Effect = DragDropEffects.Move;
            }
        }


        private void treeKhoaBoMonMonHocLopTinChi1_DragOver(object sender, DragEventArgs e)
        {
            if (e.Data.GetData(typeof(List<DataRow>)) != null)
            {
                e.Effect = DragDropEffects.Move;
            }
        }
        private void gridData_CellMouseMove(object sender, DataGridViewCellMouseEventArgs e)
        {
            if (e.Button == MouseButtons.Left)
            {
                List<DataRow> ls = GetSelectedDataRows();
                gridData.DoDragDrop(ls, DragDropEffects.Move);
            }
        }

    }
}
